/*
 * 上海远境文化传媒有限公司 版权所有
 */
package controllers;

import facade.AppContext;
import facade.base.AdminUserFacade;
import facade.base.CorpFacade;
import facade.base.EntityLogFacade;
import helper.BrowserHelper;
import helper.UrlHelper;
import helper.constants.CookieName;
import helper.constants.SessionName;
import models.base.AdminUser;
import org.apache.commons.lang3.StringUtils;
import play.Logger;
import play.data.validation.Required;
import play.data.validation.Valid;
import play.data.validation.Validation;
import util.play.CookieUtility;

/**
 * 用户登陆.
 */
public class Sessions extends WebBaseController {

    /**
     * 登陆页.
     */
    public static void index(String login) {

        // 安装版不使用 /sessions 页面登录
        if (CorpFacade.isPrivateInstallVersion()) {
            redirect(UrlHelper.getContextPath("/login"));
        }

        String lastViewUrl = session.get(SessionName.LAST_VIEW_URL);
        Logger.info("TLQ381990: lastViewUrl=%s", lastViewUrl);
        if (StringUtils.isBlank(lastViewUrl)) {
            lastViewUrl = UrlHelper.getContextPath("/main");
        }
        if (!BrowserHelper.isWeixinBrowser()) {
            // 如果有登录过，就跳转到 /main
            String userId = session.get(SessionName.SESSION_USER_KEY);
            if (StringUtils.isNotBlank(userId)) {
                AdminUser user = AdminUser.findById(userId);
                if (user != null && user.isActive()) {
                    redirect(lastViewUrl);
                }
            }
        }

        if (StringUtils.isBlank(login)) {
            login = CookieUtility.readCookie(CookieName.LOGIN_NAME);
        }

        render(login);
    }

    public static void create(@Valid @Required String login, @Valid @Required String password) {
        checkAuthenticity();

        if (Validation.hasErrors()) {
            flash.put("warn", "用户名和密码不能为空");
            index(login);
        }

        AdminUser user = AdminUserFacade.checkForLogin(login, password);
        if (user != null) {
            EntityLogFacade.log(user.id, user, AppContext.getClientType(), request.host + "/sessions 密码登录");
            session.put(SessionName.SESSION_USER_KEY, user.id);
            Application.index();
        }
        flash.put("warn", "无效的用户或密码");
        index(login);
    }

}
